package org.jb.coinche.server.business.transition;

import org.jb.coinche.client.business.message.NextTurnMessage;
import org.jb.coinche.client.business.model.Player;
import org.jb.coinche.client.business.model.Round;
import org.jb.coinche.client.business.model.RoundFinished;
import org.jb.coinche.client.business.model.RoundTurn;
import org.jb.coinche.client.business.model.RoundTurnFinished;
import org.jb.coinche.server.statemachine.Message;
import org.jb.coinche.server.statemachine.Transition;

public class RoundTurnFinishedTransition implements Transition {

	@Message
	public Object processNextTurn( RoundTurnFinished rtf, NextTurnMessage msg ) {
		
		if (rtf.getRound().isFinished()) {
			/*
			 * La partie est finie, on calcul qui a gagné
			 */
			RoundFinished rf = new RoundFinished();
			rf.setGame( rtf.getRound().getGame() );
			Round r = rtf.getRound();
			
			r.addScoreDixDeDer( rtf.getWinner().getTeam() );
			
			rf.setTeam1Score( r.getScore1() );
			rf.setTeam2Score( r.getScore2() );
			rf.setAuction( rtf.getRound().getAuction() );
			
			int contrat = r.getAuction().getValue();
			if (contrat == 160)
				contrat = 250; // capot
			
			boolean advpt = false;
			switch( r.getAuction().getCoincheMode() ) {
			case COINCHE:
				contrat *= 2;
				break;
				
			case SURCOINCHE:
				contrat *= 4;
				break;
				
			default:
				advpt = true;
				break;
			}
			
			if (r.getAuction().getTeam() == Player.Team.T1) {
				if (r.getScore1() >= r.getAuction().getValue() + 2) {
					
					// T1 a reussi son contrat
					int score1 = r.getScore1();
					if (score1 == 162)
						score1 = 250;
					
					rf.setTeam1ScoreInc( score1 + contrat );
					
					if (advpt)
						rf.setTeam2ScoreInc( 162 - r.getScore1() );
					
					rf.setWinner(Player.Team.T1);
					
				} else {
					
					// T1 n'a pas reussi son contrat					
					rf.setTeam2ScoreInc( 160 + contrat );
					
					rf.setWinner(Player.Team.T2);
				}
			} else {
				if (r.getScore2() >= r.getAuction().getValue() + 2) {
				
					// T2 a reussi son contrat						
					int score2 = r.getScore2();
					if (score2 == 162)
						score2 = 250;
					
					rf.setTeam2ScoreInc( score2 + contrat );
					
					if (advpt)
						rf.setTeam1ScoreInc( 162 - r.getScore2() );
					
					rf.setWinner(Player.Team.T2);
				} else {
					// T2 a echoué son contrat					
					rf.setTeam1ScoreInc( 160 + contrat );
					rf.setWinner(Player.Team.T1);
				}
			}
			
			r.getGame().addScore1( rf.getTeam1ScoreInc() );
			r.getGame().addScore2( rf.getTeam2ScoreInc() );
			
			return rf;
			
			
		} else {
			/*
			 * On lance juste un nouveau tour
			 */
			RoundTurn roundTurn = new RoundTurn();
			roundTurn.setCurrentPlayer( rtf.getWinner() );
			roundTurn.setRound( rtf.getRound() );
			
			return roundTurn;
		}
	}
}
